import 'dart:io';

import 'package:eshi/app/CommonFunctions.dart';
import 'package:eshi/app/shi/data/parse/FileParser.dart';
import 'package:eshi/app/shi/data/tabtxt_history.dart';
import 'package:eshi/app/shi/taxis/TabEditPage.dart';
import 'package:eshi/app/utils/FileUtils.dart';
import 'package:eshi/main.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

mixin  TabEditPageEvent on State<TabEditPage>{
  TabEditPageState get self => this as TabEditPageState;
  
  KeyEventResult onKeyDown(RawKeyDownEvent event){
    // 监听Tab键按下事件（忽略释放事件）
    switch(event.logicalKey){
          case LogicalKeyboardKey.tab :
              if(!event.isShiftPressed && self.cursorLines.length<2){
                 self.handleInput(' ' * widget.tabSpaces);
              }else{
                 self.linesTabSet(!event.isShiftPressed);
              }
              return KeyEventResult.handled;
              // //多行选择之后的tab
              // final selection =  self._controller.selection;
              // if((selection.extentOffset - selection.baseOffset).abs()>0 && self.selectionBlock.lineCount >1 ){
              //   self.linesTabSet(!event.isShiftPressed);
              //   return KeyEventResult.handled;  
              // } 
              // self.handleInput(' ' * widget.tabSpaces);
              // return KeyEventResult.handled;
          case LogicalKeyboardKey.enter:
               final cursorOffset = self.controller.selection.baseOffset;
               final text = self.controller.text;
               if(text.substring(cursorOffset).startsWith("\n")){
                 final lastLine = text.substring(text.lastIndexOf("\n",cursorOffset-1),cursorOffset);
                 self.handleInput(lastLine.replaceFirst(RegExp(r"\S.+"), ""));
                 return KeyEventResult.handled;
               }
          case LogicalKeyboardKey.slash:  //ctrl+/
            if(event.isControlPressed){
               self.linesCommentSet();
               return KeyEventResult.handled;
            }
            
      }
      return KeyEventResult.ignored;
  }

  static  loadDtt(String path) async{
      File file = File(path);
      var name = file.name;
     if(await FileParser.assetsFile("assets/txt/$name.txt").exists()){
          return "$name已经存在无法导入！";
      }
      await FileParser.importDtt(file.path);
      var history = await TabTxtHistory.load(name);
      mainWidgetKey.currentState?.changeHistory(history);
      return "";
  }
  onLoadFile([bool inDoc=true]) async {
     List<String> errorInfo=[];
    //添加文件到对应的目录中
    await FileParser.pickMultipleFiles((name,file) async {
        //如果是分享的文件 
        if(file.name.endsWith(".dtt")){
            var msg = await loadDtt(file.path);
            if(msg.isNotEmpty) errorInfo.add("$name已经存在无法导入！");
            else self.close(); 
            // if(await FileParser.assetsFile("assets/txt/$name.txt").exists()){
            //     errorInfo.add("$name已经存在无法导入！");
            //     return;
            // }
            // await FileParser.importDtt(file.path);
            // TabTxtHistory.load(name).then((history){
            //     mainWidgetKey.currentState?.changeHistory(history);
            //     self.close();
            //     // self._controller.text = TabTxtHistory.allTxt[name]!;
            // });
            return;
        }
        //判断文件中是不是包含关键字
        // if(inDoc && !self.controller.text.contains(name)){
        //   errorInfo.add("${file.name}界面中没有匹配到关键字");
        //   return;
        // }
        //如果获取类型失败
        var type = FileUtils.getMimeType(file);
        if(type==null){
          errorInfo.add("${file.name}类型不确定丢弃！");
          return;
        } 
        //判断类型是不是支持
        if(!await FileParser.assetsDirectory("assets/$type").exists()){
          errorInfo.add("${file.name}类型不支持丢弃！");
          return;  
        }
        //添加文件和标签 
        self.importFiles.add(file);
        self.addMark(type,name);
    });
    if(errorInfo.isNotEmpty) {
      msg(errorInfo.join("\n"),bgColor: Colors.blueGrey,sec:5);
    }
  }

  onSave(){
     if(self.importFiles.isNotEmpty) {
        self.importFiles.forEach(FileParser.importFile);
        msg("保存(${self.importFiles.length})个文件成功!");
      }
      widget.onChange(self.controller.text,self.marksGroup,self.titleTextController.text);
  }
}

extension on File {
  // ignore: unused_element
  String get exName => path.substring(path.lastIndexOf('.')).toLowerCase();
  String get baseName => path.split(Platform.pathSeparator).last;
  String get name => baseName.substring(0,baseName.lastIndexOf('.'));
}